import 'dart:io';

import 'package:flutter/material.dart';
import 'package:permission/permission.dart';
import 'package:time/test/test_file.dart';

class FileApp extends StatelessWidget {
  const FileApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var arguments = ModalRoute.of(context)?.settings.arguments as String;
    print(arguments);
    return MaterialApp(
        title: "文件",
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: FilePage(() => {Navigator.of(context).pop("反悔啦")}));
  }
}

class FilePage extends StatefulWidget {
  final Function toClose;

  const FilePage(this.toClose, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // ignore: no_logic_in_create_state
    return FilePageState(toClose);
  }
}

class FilePageState extends State<StatefulWidget> {
  var filePath = "";
  var fileInfo = "";
  var fileContent = "";

  final Function toClose;

  FilePageState(this.toClose) {
    initFilePath();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("文件")),
      body: Column(
        children: [
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "关闭页面",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => toClose()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "获取权限",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => getPermission()),
          Text(filePath),
          Text(fileInfo),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "文件信息",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => showFileInfo()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "创建文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => createFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "删除文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => deleteFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "写文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => writeFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "添加内容",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => writeFileAccess()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "读文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => readFile()),
          Text(fileContent)
        ],
      ),
    );
  }

  showFileInfo() async {
    var file = File(filePath);
    file.exists().then((value) {
      fileInfo = ("exist:" + value.toString());
      updateFileInfo();
      if (value) {
        file.length().then((value) {
          fileInfo += ",大小:" + value.toString();
          setState(() {
            fileInfo;
          });
        });
      }
    });
  }

  updateFileInfo() {
    setState(() {
      fileInfo;
    });
  }

  /// 获取存储权限
  getPermission() {
    Permission.requestPermissions([Permission.storage]);
  }

  void initFilePath() {
    TestFile().getPath().then((value) {
      setState(() {
        filePath = value + "/test.json";
        if (Platform.isMacOS) {
          filePath = "~/test.json";
        }
      });
    }).onError((error, stackTrace) {
      print("onError:2");
      if (Platform.isMacOS) {
        filePath = "~/test.json";
      }
    }).catchError((any) {
      print("catchError:" + Platform.isMacOS.toString());
      if (Platform.isMacOS) {
        filePath = "~/test.json";
      }
    });
  }

  createFile() {
    var file = File(filePath);
    file.exists().then((value) {
      if (!value) {
        file.create().then((value) {
          showFileInfo();
          readFile();
        });
      }
    });
  }

  deleteFile() async {
    var file = File(filePath);
    await file.delete();
    showFileInfo();
  }

  writeFile() async {
    var file = File(filePath);
    await file.writeAsString("Hello World!\n");
    showFileInfo();
    readFile();
  }

  writeFileAccess() async {
    var file = File(filePath);
    var ioSink = file.openWrite(mode: FileMode.append);
    ioSink.write(DateTime.now().millisecondsSinceEpoch.toString() +
        "Hello World! (添加内容) \n");
    ioSink.flush();
    showFileInfo();
    readFile();
  }

  readFile() async {
    var file = File(filePath);
    var s = await file.readAsString();
    setState(() {
      fileContent = s;
    });
  }
}
